package com.yzt.sys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yzt.base.kit.Base;
import com.yzt.config.websocket.WebSocketService;
import com.yzt.sys.entity.RoleMenu;
import com.yzt.sys.service.IRoleMenuService;

/**
 * <p>
 * 角色菜单关联表 前端控制器
 * </p>
 *
 * @author Y
 * @since 2020-12-21
 */
@RestController
@RequestMapping("/sys/roleMenu")
public class RoleMenuController {

	@Autowired
	private IRoleMenuService roleMenuService;
	@Autowired
	private WebSocketService webSocketService;

	@GetMapping("checked/{roleId}")
	public Base<Object> getCheckedList(@PathVariable("roleId") long roleId) {
		return Base.okData(roleMenuService.getMenuIdList(roleId));
	}

	@PostMapping("")
	@Transactional(rollbackFor = Exception.class)
	public Base<Object> menuAssignment(Long[] menuIds, long roleId) throws Exception {
		roleMenuService.remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));
		boolean b = false;
		for (Long menuId : menuIds) {
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setRoleId(roleId);
			roleMenu.setMenuId(menuId);
			b = roleMenuService.save(roleMenu);
			if (!b) {
				throw new Exception();
			}
		}
		webSocketService.sendMsgToAll(JSON.toJSONString(Base.ok(600, "刷新菜单")));
		return Base.ok();
	}

}
